package edu.noteBook.controller;

import edu.noteBook.Pojo.User;
import edu.noteBook.utils.JwtUtil;
import edu.noteBook.utils.R;
import edu.noteBook.service.UserService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/user")
@Validated
@CrossOrigin(origins = "http://localhost:5500,http://localhost:8080", allowCredentials = "true")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param username
     * @param password
     * @return token，便于后面进行提取用户身份
     */
    @PostMapping("/{username}/{password}")
    public R login(@PathVariable("username") String username,
                   @PathVariable("password") String password) {
        User user = userService.login(username, password);
        if (user != null) {
            System.out.println(user);
            String token = JwtUtil.generateToken(user);
            return new R(true, token, "账号密码正确，登录成功！！！欢迎" + user.getUsername());
        } else {
            return new R(false, null, "账号密码错误，登录失败，请重新输入。");
        }
    }


    /**
     * 获取当前用户数据
     * @param authHeader
     * @return user
     */
    @GetMapping("/getCurrentUser")
    public R getCurrentUser(@RequestHeader("Authorization") String authHeader) {
        try {
//            System.out.println("收到的Authorization header: " + authHeader);
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                System.out.println("Authorization header格式错误");
                return new R(false, null, "无效的token格式");
            }
            String token = authHeader.substring(7);
//            System.out.println("提取的token: " + token);
            // 先验证token
            if (!JwtUtil.validateToken(token)) {
                System.out.println("token验证失败");
                return new R(false, null, "无效的token");
            }
            Claims claims = JwtUtil.parseToken(token);
//            System.out.println("解析后的claims: " + claims);
            Integer userId = claims.get("id", Integer.class);
            System.out.println("从token中获取的用户ID: " + userId);
            if (userId == null) {
//                System.out.println("token中没有用户ID");
                return new R(false, null, "token中无用户信息");
            }
            User currentUser = userService.queryUserByID(userId);
//            System.out.println("查询到的用户信息: " + currentUser);
            if (currentUser == null) {
                System.out.println("未找到用户信息");
                return new R(false, null, "未找到用户信息");
            }
            return new R(true, currentUser);
        } catch (Exception e) {
            System.out.println("处理getCurrentUser请求时发生错误: " + e.getMessage());
            e.printStackTrace();
            return new R(false, null, "获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 退出登录,清楚token数据
     * @param session
     * @return 退出成功
     */
    @PostMapping("/logout")
    public R logout(HttpSession session) {
        session.removeAttribute("currentUser");
        return new R(true, "退出登录成功");
    }

    /**
     * 注册
     * @param username
     * @param password
     * @param email
     * @param phone
     * @param address
     * @param avatar
     * @param request
     * @return 返回是否注册成功
     */
    @PostMapping
    public R addUser(   @RequestParam("username") String username,
                         @RequestParam("password") String password,
                         @RequestParam("email") String email,
                         @RequestParam("phone") String phone,
                         @RequestParam("address") String address,
                         @RequestParam("avatar") MultipartFile avatar,
                         HttpServletRequest request) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setPhone(phone);
        user.setAddress(address);
        System.out.println(user);
        String heading = saveFiles(avatar, request);
        user.setAvatar(heading);
        Date now = new Date();
        user.setCreateTime(now);
        if (userService.addUser(user)) {
            return new R(true, "注册成功，请登录。");
        } else {
            return new R(false, "注册失败，请重新注册。");
        }
    }

    /**
     * 删除用户
     * @param id
     * @return 删除成功
     */
    @DeleteMapping("/{id}")
    public R deleteUser(@PathVariable Integer id){
        if (userService.deleteUser(id)){
            return new R(true,"删除成功。");
        }else{
            return new R(false,"删除失败。");
        }
    }

    /**
     * 修改用户信息
     * @param id
     * @param username
     * @param email
     * @param phone
     * @param avatar
     * @param token
     * @param request
     * @return 修改成功
     */
    @PutMapping
    public R updateUser(@RequestParam(name = "id") Integer id,
                        @RequestParam(name = "username", required = false) String username,
                        @RequestParam(name = "email", required = false) String email,
                        @RequestParam(name = "phone", required = false) String phone,
                        @RequestParam(name = "avatar", required = false) MultipartFile avatar,
                        @RequestHeader("Authorization") String token,
                        HttpServletRequest request) {
        try {
            // 创建用户对象
            User user = new User();
            user.setId(id);  // 设置用户ID
            user.setUsername(username);
            user.setEmail(email);
            user.setPhone(phone);

            // 如果有上传头像，处理头像
            if (avatar != null && !avatar.isEmpty()) {
                user.setAvatar(saveFiles(avatar, request));
            }

            // 更新用户信息
            if (userService.updateUser(user) > 0) {
                return new R(true, "修改成功");
            } else {
                return new R(false, "修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new R(false, "修改失败：" + e.getMessage());
        }
    }

    private String saveFiles(MultipartFile file, HttpServletRequest request){
        ServletContext servletContext = request.getServletContext();
        String realPath = servletContext.getRealPath("/upload");
        File dir = new File(realPath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        String fileType =  file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = "/" + UUID.randomUUID().toString() + fileType;
        System.out.println("fileName---->"+fileName);
        File destFile = new File(dir.getAbsolutePath() + fileName);
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "/upload"+fileName;
    }

}
